﻿using System.Collections.Generic;
using System.Linq;

using Preactor.ObjectModel.Attributes;
using Preactor.ObjectModel.Entities;
using Preactor.ObjectModel.Interfaces;
using Preactor.ObjectModel.Utilities;

namespace Preactor.ObjectModel.BaseTypes
{
    public class ResourceGroup : PreactorRecord, IResourceGroup<IResource>
    {
        public ResourceGroup(PrimaryKey id, PreactorObjectModel preactorObjectModel)
            : base(id, preactorObjectModel)
        {
            GetResources();
        }

        [PreactorField("RESOURCE GROUP NAME", FieldDeclarationType.FieldClassification)]
        public string Name
        {
            get { return (string)GetValue("Name"); }
            set { SetValue("Name", value); }
        }

        public IEnumerable<string> ResourceNames { get; set; }

        [PreactorField("Resources", FieldDeclarationType.FieldName)]
        public IEnumerable<IResource> Resources { get; set; }

        private void GetResources()
        {
            // Get the values in the Matrix field.
            List<List<string>> matrixResources = ReadMatrixFieldString<string>(PreactorObjectModel.GetFormatFieldPair<IResourceGroup<IResource>>(x => x.Resources));

            // We have an AUTO LIST so we can flatten the matrix
            ResourceNames = matrixResources.SelectMany(item => item);
            Resources = ResourceNames.Select(name => PreactorObjectModel.GetResourceByName(name));
        }
    }
}